package leetcode;

import java.util.*;

/**
 * 给你一个包含 n 个整数的数组nums，判断nums中是否存在三个元素 a，b，c ，使得a + b + c = 0 ？
 * 请你找出所有和为 0 且不重复的三元组。
 */
public class 三数之和 {

    public List<List<Integer>> threeSum(int[] nums) {
        Set<String> set = new HashSet<>();
        List<List<Integer>> result = new ArrayList<>();
        if (nums == null || nums.length <= 0) {
            return result;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            // 数组是从小到大进行排序的
            if(nums[i] > 0) {
                return result;
            }
            int ele = nums[i];
            int low = i + 1;
            int high = nums.length - 1;
            while (low < high) {
                int sum = ele + nums[low] + nums[high];
                if (sum == 0) {
                    StringBuilder str = new StringBuilder();
                    List<Integer> list = new ArrayList<>();
                    list.add(ele);
                    list.add(nums[low]);
                    list.add(nums[high]);
                    str.append(ele);
                    str.append(nums[low]);
                    str.append(nums[high]);
                    while (low < high && nums[low] == nums[low + 1]) {
                        low++;
                    }
                    while (low < high && nums[high] == nums[high - 1]) {
                        high--;
                    }
                    low++;
                    high--;
                    if (set.contains(str.toString())) {
                        continue;
                    }
                    set.add(str.toString());
                    result.add(list);
                }
                if (sum < 0) {
                    low++;
                }
                if (sum > 0) {
                    high--;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {

    }
}
